<?php
/**
 * Created by PhpStorm.
 * User: iiinsomnia
 * Date: 2017/11/25
 * Time: 17:47
 */
namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Container\Container;
use Laravel\Lumen\Application;

class AuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('access-token');
        if (empty($token)) {
            return response()->json([
                'code' => 1001,
                'err'  => true,
                'msg'  => '用户未授权',
            ], 200);
        }
        $user = User::whereToken($token)->first();
        if (empty($user)) {
            return response()->json([
                'code' => 1001,
                'err'  => true,
                'msg'  => '用户未授权',
            ], 200);
        }
        Container::getInstance()->singleton('loginUser',function() use ($user){
            return $user;
        });
        return $next($request);
    }
}